package com.secneo.appshare.activities;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.json.JSONObject;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.gfan.demo.TEA;
import com.secneo.appshare.AppShareApplication;
import com.secneo.appshare.R;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.ActivityUtil;
import com.secneo.appshare.common.Base64;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.common.DownApp;
import com.secneo.mp.http.HttpConnect;
import com.secneo.mp.util.MD5;

public class DownloadActivity extends CommonMenuActivity
{
	private ListView mShopList;
	private List<ShopItem> shopList;
	private ShopsAdapter mShopAdapter;
	private String mPackageName = "";
	private String mAppName = "";
	private String mAppVersion = "";
	private String mAppSize = "";
	private String mDownUrl = "";
	private String mIconUrl = "";
	private byte[] mIconBytes;
	private String mAppDes = "";

	public static final int MSG_GET_SHOP1_OK = 101;
	public static final int MSG_GET_SHOP2_OK = 102;
	public static final int MSG_GET_SHOP3_OK = 103;
	public static final int MSG_GET_SHOP4_OK = 104;
	public static final int MSG_GET_SHOP5_OK = 105;
	public static final int MSG_GET_SHOP6_OK = 106;
	public static final int MSG_GET_SHOP7_OK = 107;
	private boolean action_msg_published = false;
	
	
	// for 安卓必备
	private String mAppName_shop6 = "";
	private String mAppVersion_shop6 = "";
	private String mAppSize_shop6 = "";
	private String mDownUrl_shop6 = "";
	private boolean mNoInfo_shop6 = false;
	private GetShop6Thread mGetShop6Thread;
	private int indexAnzhuo = 0;
	// for 安极市场
	private String mAppName_shop7 = "";
	private String mAppVersion_shop7 = "";
	private String mAppSize_shop7 = "";
	private String mDownUrl_shop7 = "";
	private boolean mNoInfo_shop7 = false;
	private GetShop7Thread mGetShop7Thread;
	private int indexAnji = 1;
	// for 安丰
	private String mAppName_shop3 = "";
	private String mAppVersion_shop3 = "";
	private String mAppSize_shop3 = "";
	private String mDownUrl_shop3 = "";
	private boolean mNoInfo_shop3 = false;
	private GetShop3Thread mGetShop3Thread;
	private int indexAnfeng = 4;
	// for 历趣
	private String mAppName_shop2 = "";
	private String mAppVersion_shop2 = "";
	private String mAppSize_shop2 = "";
	private String mDownUrl_shop2 = "";
	private boolean mNoInfo_shop2 = false;
	private GetShop2Thread mGetShop2Thread;
	private int indexLiqu = 5;
	// for 机锋
	private String mAppName_shop4 = "";
	private String mAppVersion_shop4 = "";
	private String mAppSize_shop4 = "";
	private String mDownUrl_shop4 = "";
	private boolean mNoInfo_shop4 = false;
	private GetShop4Thread mGetShop4Thread;
	private int indexJifeng = 2;
	// for 优亿
	private String mAppName_shop5 = "";
	private String mAppVersion_shop5 = "";
	private String mAppSize_shop5 = "";
	private String mDownUrl_shop5 = "";
	private boolean mNoInfo_shop5 = false;
	private GetShop5Thread mGetShop5Thread;
	private int indexEoe = 3;
	
	private int indexBang = 6;

	private class ShopItem
	{
		public String app_name;
		public int shop_icon;
		public String shop_name;
		public String shop_size;
		public String shop_word;
		public String shop_url;
		public String app_version;
		public String app_size;
		public String down_url;
		public boolean noInfo;
	}

	private Handler mHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			refreshShopInfo(msg.what);
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.appshare_download);
		AppShareApplication.getInstance().addActivity(this);
		Bundle bundle = getIntent().getExtras();
		mPackageName = bundle.getString("package_name");
		mAppName = bundle.getString("app_name");
		mAppVersion = bundle.getString("app_version");
		mAppSize = bundle.getString("app_size");
		mDownUrl = bundle.getString("down_url");
		mIconUrl = bundle.getString("icon_url");
		mIconBytes = bundle.getByteArray("app_icon_array");
		mAppDes = bundle.getString("app_des");
		action_msg_published = false;

		shopList = new ArrayList<ShopItem>();
		// 安卓必备
		ShopItem shop6 = new ShopItem();
		shop6.app_name = "";
		shop6.shop_icon = R.drawable.icon_azbb;
		shop6.shop_name = "安卓必备";
		shop6.shop_size = "681181";
		shop6.shop_word = "安卓必备，游戏应用啥都有！";
		shop6.shop_url = "http://www.bangcle.com/hezuo/azbb.apk";
		shop6.app_version = "";
		shop6.app_size = "";
		shop6.down_url = "";
		shop6.noInfo = false;
		shopList.add(shop6);
		// 安极
		ShopItem shop7 = new ShopItem();
		shop7.app_name = "";
		shop7.shop_icon = R.drawable.icon_anji;
		shop7.shop_name = "安极市场";
		shop7.shop_size = "";
		shop7.shop_word = "安极市场，三万款安卓应用免费下！";
		shop7.shop_url = "";
		shop7.app_version = "";
		shop7.app_size = "";
		shop7.down_url = "";
		shop7.noInfo = false;
		shopList.add(shop7);
		// 机锋
		ShopItem shop4 = new ShopItem();
		shop4.app_name = "";
		shop4.shop_icon = R.drawable.icon_jifeng;
		shop4.shop_name = "机锋市场";
		shop4.shop_size = "923572";
		shop4.shop_word = "机锋市场，最优秀的中国应用市场！";
		shop4.shop_url = "http://www.bangcle.com/hezuo/jfsc.apk";
		shop4.app_version = "";
		shop4.app_size = "";
		shop4.down_url = "";
		shop4.noInfo = false;
		shopList.add(shop4);
		// 优亿
		ShopItem shop5 = new ShopItem();
		shop5.app_name = "";
		shop5.shop_icon = R.drawable.icon_eoe;
		shop5.shop_name = "优亿市场";
		shop5.shop_size = "732055";
		shop5.shop_word = "优亿市场，游戏最多应用最全！";
		shop5.shop_url = "http://www.bangcle.com/hezuo/yysc.apk";
		shop5.app_version = "";
		shop5.app_size = "";
		shop5.down_url = "";
		shop5.noInfo = false;
		shopList.add(shop5);
		// 安丰
		ShopItem shop1 = new ShopItem();
		shop1.app_name = "";
		shop1.shop_icon = R.drawable.icon_anfeng;
		shop1.shop_name = "安丰下载";
		shop1.shop_size = "610459";
		shop1.shop_word = "安丰下载，极速安全下载！";
		shop1.shop_url = "http://www.bangcle.com/hezuo/afxz.apk";
		shop1.app_version = "";
		shop1.app_size = "";
		shop1.down_url = "";
		shop1.noInfo = false;
		shopList.add(shop1);
		// 历趣
		ShopItem shop3 = new ShopItem();
		shop3.app_name = "";
		shop3.shop_icon = R.drawable.icon_liqu;
		shop3.shop_name = "历趣市场";
		shop3.shop_size = "1326187";
		shop3.shop_word = "历趣市场，感受掌上乐趣！";
		shop3.shop_url = "http://www.bangcle.com/hezuo/lq.apk";
		shop3.app_version = "";
		shop3.app_size = "";
		shop3.down_url = "";
		shop3.noInfo = false;
		shopList.add(shop3);
		// 分享商店
		ShopItem shop2 = new ShopItem();
		shop2.app_name = mAppName;
		shop2.shop_name = "安卓分享";
		shop2.app_version = mAppVersion;
		shop2.app_size = mAppSize;
		shop2.down_url = mDownUrl;
		shop2.shop_word = "App Store，海量内容下载！";
		if (mDownUrl.equals(""))
			shop2.noInfo = true;
		else
			shop2.noInfo = false;
		shopList.add(shop2);

		mShopList = (ListView) findViewById(R.id.listview_shops);
		mShopList.setDivider(getResources().getDrawable(R.drawable.list_divider));
		mShopAdapter = new ShopsAdapter(DownloadActivity.this, shopList);
		mShopList.setAdapter(mShopAdapter);

		Button retBtn = (Button) findViewById(R.id.img_ret);
		retBtn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		});
		Button localShopBtn = (Button) findViewById(R.id.localShop);
		localShopBtn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent it = new Intent(Intent.ACTION_VIEW);
				it.setData(Uri.parse("market://search?q=pname:" + mPackageName));
				it = Intent.createChooser(it, null);
				startActivity(it);
			}
		});

		mGetShop2Thread = new GetShop2Thread(DownloadActivity.this, mHandler);
		mGetShop2Thread.start();
		
		mGetShop3Thread = new GetShop3Thread(DownloadActivity.this, mHandler);
		mGetShop3Thread.start();
		
		mGetShop4Thread = new GetShop4Thread(DownloadActivity.this, mHandler);
		mGetShop4Thread.start();
		
		mGetShop5Thread = new GetShop5Thread(DownloadActivity.this, mHandler);
		mGetShop5Thread.start();
		
		mGetShop6Thread = new GetShop6Thread(DownloadActivity.this, mHandler);
		mGetShop6Thread.start();
		
		mGetShop7Thread = new GetShop7Thread(DownloadActivity.this, mHandler);
		mGetShop7Thread.start();
	}
	
	private void refreshShopInfo(int index)
	{
		mShopAdapter.updateInfo(index);
		mShopList.invalidateViews();
	}

	public class GetShop2Thread extends Thread
	{
		private Context ctx;
		private Handler handler;
		private boolean isStop;

		public synchronized void stopRun()
		{
			isStop = true;
			this.interrupt();
		}

		public GetShop2Thread(Context c, Handler handler)
		{
			this.handler = handler;
			this.ctx = c;
			this.isStop = false;
		}

		public void run()
		{
			try
			{
				String server_url = "http://open.liqucn.com/android/5003.php?op=packagename_detail&package=" + mPackageName;
				try
				{
					HttpConnect http = new HttpConnect();
					String result = http.connectByGetString(server_url, null);
					
					if (result == null || result.equals("") || result.equals("2001"))
					{
						Log.d("MyTag", "Shop Liqu no response!");
						mNoInfo_shop2 = true;
					}
					else
					{
						DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
						DocumentBuilder dbuilder = dbf.newDocumentBuilder();
						InputSource is = new InputSource(new StringReader(result));
						is.setEncoding("UTF-8");
						Document dom = dbuilder.parse(is);
						String tmpName = dom.getElementsByTagName("appTitle").item(0).getAttributes().getNamedItem("label").getNodeValue();
						mAppName_shop2  = new String(tmpName.getBytes("ISO-8859-1"), "UTF-8");
						mAppVersion_shop2 = dom.getElementsByTagName("applicationDetail").item(0).getAttributes().getNamedItem("versionName").getNodeValue();
						mAppSize_shop2 = dom.getElementsByTagName("applicationDetail").item(0).getAttributes().getNamedItem("size").getNodeValue();
						String downPost = dom.getElementsByTagName("guidepost").item(0).getAttributes().getNamedItem("uri").getNodeValue();
						
						String result2 = http.connectByGetString(downPost, null);
						if (result2 == null || result2.equals("") || result2.equals("2001"))
						{
							Log.d("MyTag", "Shop Liqu no response2!");
							mNoInfo_shop2 = true;
						}
						else
						{
							is = new InputSource(new StringReader(result2));
							is.setEncoding("UTF-8");
							dom = dbuilder.parse(is);
							mDownUrl_shop2 = dom.getElementsByTagName("guidepost").item(0).getAttributes().getNamedItem("uri").getNodeValue();
						}
					}
					Message msg = new Message();
					msg.what = MSG_GET_SHOP2_OK;
					mHandler.sendMessage(msg);
					
				} catch (Exception e)
				{
					Log.d("MyTag", "Shop Liqu error1:" + e.getMessage());
					mNoInfo_shop2 = true;
					Message msg = new Message();
					msg.what = MSG_GET_SHOP2_OK;
					mHandler.sendMessage(msg);
				}

			} catch (Exception ex)
			{
				Log.d("MyTag", "Shop Liqu error2:" + ex.getMessage());
				mNoInfo_shop2 = true;
				Message msg = new Message();
				msg.what = MSG_GET_SHOP2_OK;
				mHandler.sendMessage(msg);
			}
		}
	}
	
	public class GetShop3Thread extends Thread
	{
		private Context ctx;
		private Handler handler;
		private boolean isStop;

		public synchronized void stopRun()
		{
			isStop = true;
			this.interrupt();
		}

		public GetShop3Thread(Context c, Handler handler)
		{
			this.handler = handler;
			this.ctx = c;
			this.isStop = false;
		}

		public void run()
		{
			try
			{
				String server_url = "http://www.anfone.com/qsoft.html?pkgname=" + mPackageName;
				try
				{
					HttpConnect http = new HttpConnect();
					String res = http.connectByGetString(server_url, null);
					if (res == null || res.equals("") || res.equals("403"))
					{
						Log.d("MyTag", "Shop Anfeng no response!");
						mNoInfo_shop3 = true;
					}
					else
					{
				    	JSONObject json = new JSONObject(res);
				    	mAppName_shop3 = json.getString("name");
				    	mAppName_shop3  = new String(mAppName_shop3.getBytes("ISO-8859-1"), "UTF-8");
				    	
						mAppVersion_shop3 = json.getString("version");
						mDownUrl_shop3 = json.getString("url");

						mAppSize_shop3 = json.getString("size");
						
						double sizeInt=0;
						int sizeIntB=0;
						int length = mAppSize_shop3.length();
						if(length>2){
							String measure = "";
							measure = mAppSize_shop3.substring(length-2, length);
							if("MB".equalsIgnoreCase(measure)){
								Log.e("anfeng", "anfeng size has a measure of MB");
								mAppSize_shop3 = mAppSize_shop3.substring(0, length-2);
								sizeInt = Double.valueOf(mAppSize_shop3);
								sizeIntB = (int)(sizeInt * 1024 * 1024);
							}
							else if("KB".equalsIgnoreCase(measure)){
								Log.e("anfeng", "anfeng size has a measure of KB");
								mAppSize_shop3 = mAppSize_shop3.substring(0, length-2);
								sizeInt = Double.valueOf(mAppSize_shop3);
								sizeIntB = (int)(sizeInt * 1024);
							}
							else {
								measure = mAppSize_shop3.substring(length-1, length);
								if("B".equalsIgnoreCase(measure)){
									Log.e("anfeng", "anfeng size has a measure of B");
									mAppSize_shop3 = mAppSize_shop3.substring(0, length-1);
									sizeInt = Double.valueOf(mAppSize_shop3);
									sizeIntB = (int)sizeInt;
								}
								else{
									Log.e("anfeng", "anfeng size string has no measure");
									sizeInt = Double.valueOf(mAppSize_shop3);
									sizeIntB = (int)sizeInt;
								}
							}
						}
						else{
							Log.e("anfeng", "anfeng size string is too short(<2)");
							sizeInt = Double.valueOf(mAppSize_shop3);
							sizeIntB = (int)sizeInt;
						}
						
						mAppSize_shop3 = String.valueOf(sizeIntB);
					}
					Message msg = new Message();
					msg.what = MSG_GET_SHOP3_OK;
					mHandler.sendMessage(msg);
					
				} catch (Exception e)
				{
					Log.d("MyTag", "Shop Anfeng error1:" + e.getMessage());
					mNoInfo_shop3 = true;
					Message msg = new Message();
					msg.what = MSG_GET_SHOP3_OK;
					mHandler.sendMessage(msg);
				}

			} catch (Exception ex)
			{
				Log.d("MyTag", "Shop Anfeng error2:" + ex.getMessage());
				mNoInfo_shop3 = true;
				Message msg = new Message();
				msg.what = MSG_GET_SHOP3_OK;
				mHandler.sendMessage(msg);
			}
		}
	}
	
	private String JifengInOut(String reqUrl, String inputStr)
	{
		try
		{
	        byte[] key = "mappn#share!@)%^".getBytes();
	        ByteArrayOutputStream b = new ByteArrayOutputStream();
	        GZIPOutputStream zOut = new GZIPOutputStream(b);
	        zOut.write(inputStr.getBytes("UTF-8"));
	        zOut.flush();
	        zOut.close();
	        b.close();
	        String requestStr = Base64.encodeBytes(new TEA().encrypt(b.toByteArray(), key));
	
	        URL url = new URL(reqUrl);
	        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	        conn.setRequestMethod("POST");
	        String tmpInfo = android.os.Build.MODEL + "/" + android.os.Build.VERSION.RELEASE + "/AppShare/1.3.0/1034";
	        conn.setRequestProperty("User-Agent", tmpInfo);
	        conn.setDoInput(true);
	        conn.setDoOutput(true);
	        Writer writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
	        writer.write(requestStr);
	        writer.close();
	        
	        int responseCode = conn.getResponseCode();
	        if (responseCode == 200)
	        {
	            InputStream responseStream = conn.getInputStream();
	            Reader responseReader = new InputStreamReader(responseStream, "UTF-8");
	            StringWriter buffWriter = new StringWriter();
	            char[] buf = new char[100];
	            int length = 0;
	            while ((length = responseReader.read(buf)) > 0) 
	            {
	                buffWriter.write(buf, 0, length);
	            }
	            buffWriter.close();
	            responseStream.close();
	            String responseStr = buffWriter.toString();
	            
	            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
	            outStream.write(new TEA().decrypt(Base64.decode(responseStr), key));
	            GZIPInputStream zIn = new GZIPInputStream(new ByteArrayInputStream(outStream.toByteArray()));
	            outStream = new ByteArrayOutputStream();
	            byte[] buff = new byte[4096];
	            length = 0;
	            while ((length = zIn.read(buff)) >= 0) 
	            {
	                outStream.write(buff, 0, length);
	            }
	            String responseXml = new String(outStream.toByteArray(), "UTF-8");
	            conn.disconnect();
	            return responseXml;
	        }
	        else
	        {
	        	conn.disconnect();
	        	return null;
	        }
        
		} catch (Exception ex)
		{
			Log.d("MyTag", "GetShop4Thread error:" + ex.getMessage());
			return null;
		}
	}
	
	public class GetShop4Thread extends Thread
	{
		private Context ctx;
		private Handler handler;
		private boolean isStop;

		public synchronized void stopRun()
		{
			isStop = true;
			this.interrupt();
		}

		public GetShop4Thread(Context c, Handler handler)
		{
			this.handler = handler;
			this.ctx = c;
			this.isStop = false;
		}

		public void run()
		{
			try
			{
		        String reqXml = "<request version=\"1\">"
		                + "<packagename>"+ mPackageName +"</packagename>"
		                + "</request>";
		        
		        String responseXml = JifengInOut("http://api.gfan.com/market/api/getDetail", reqXml);
	            if(responseXml != null)
	            {
					DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
					DocumentBuilder dbuilder = dbf.newDocumentBuilder();
					InputSource is = new InputSource(new StringReader(responseXml));
					is.setEncoding("UTF-8");
					Document dom = dbuilder.parse(is);
					mAppName_shop4 = dom.getElementsByTagName("product").item(0).getAttributes().getNamedItem("name").getNodeValue();
					mAppVersion_shop4 = dom.getElementsByTagName("product").item(0).getAttributes().getNamedItem("version_name").getNodeValue();
					mAppSize_shop4 = dom.getElementsByTagName("product").item(0).getAttributes().getNamedItem("app_size").getNodeValue();
					String app_id = dom.getElementsByTagName("product").item(0).getAttributes().getNamedItem("p_id").getNodeValue();
					
			        String reqXml2 = "<request version=\"1\">"
		                + "<p_id>"+ app_id +"</p_id>"
		                + "<source_type>0</source_type>"
		                + "</request>";
		        
			        String responseXml2 = JifengInOut("http://api.gfan.com/market/api/getDownloadUrl", reqXml2);
			        if(responseXml2 != null)
			        {
			        	is = new InputSource(new StringReader(responseXml2));
						is.setEncoding("UTF-8");
						dom = dbuilder.parse(is);
						mDownUrl_shop4 = dom.getElementsByTagName("download_info").item(0).getAttributes().getNamedItem("url").getNodeValue();
			        }
			        else
			        	mNoInfo_shop4 = true;
	            }
	            else
	            	mNoInfo_shop4 = true;

			} catch (Exception ex)
			{
				Log.d("MyTag", "Shop Jifeng error:" + ex.getMessage());
				mNoInfo_shop4 = true;
			}
			finally
			{
				Message msg = new Message();
				msg.what = MSG_GET_SHOP4_OK;
				mHandler.sendMessage(msg);
			}
		}
	}
	
	public class GetShop5Thread extends Thread
	{
		private Context ctx;
		private Handler handler;
		private boolean isStop;

		public synchronized void stopRun()
		{
			isStop = true;
			this.interrupt();
		}

		public GetShop5Thread(Context c, Handler handler)
		{
			this.handler = handler;
			this.ctx = c;
			this.isStop = false;
		}

		public void run()
		{
			try
			{
				Calendar curr = Calendar.getInstance();
				long timeInSec = curr.getTimeInMillis()/1000;
				String sigSource = "api_keyDICOGBLUM1AJR0EVEFBPTAtimestamp"+timeInSec+"api_secretPES097MOZZOPVLHDEHOXO60JRWNBBUYJJRUYRQKSO8";
				String sig = MD5.getMD5(sigSource.getBytes());
				String server_url = "http://api.eoeandroid.com/bang?api_key=DICOGBLUM1AJR0EVEFBPTA&api_sig="+sig+"&timestamp="+timeInSec+"&format=xml&v=1.0&package=" + mPackageName;
				try
				{
					HttpConnect http = new HttpConnect();
					String result = http.connectByGetString(server_url, null);
					
					if (result == null || result.equals("") || result.equals("2001"))
					{
						Log.d("MyTag", "Shop Eoe no response!");
						mNoInfo_shop5 = true;
					}
					else
					{
						DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
						DocumentBuilder dbuilder = dbf.newDocumentBuilder();
						InputSource is = new InputSource(new StringReader(result));
						is.setEncoding("UTF-8");
						Document dom = dbuilder.parse(is);
						mAppName_shop5 = dom.getElementsByTagName("applicationDetail").item(0).getAttributes().getNamedItem("appName").getNodeValue();
						mAppVersion_shop5 = dom.getElementsByTagName("applicationDetail").item(0).getAttributes().getNamedItem("versionName").getNodeValue();
						mAppSize_shop5 = dom.getElementsByTagName("applicationDetail").item(0).getAttributes().getNamedItem("size").getNodeValue();
						mDownUrl_shop5 = dom.getElementsByTagName("download").item(0).getAttributes().getNamedItem("uri").getNodeValue();
					}
					
				} catch (Exception e)
				{
					Log.d("MyTag", "Shop Eoe error1:" + e.getMessage());
					mNoInfo_shop5 = true;
				}

			} catch (Exception ex)
			{
				Log.d("MyTag", "Shop Eoe error2:" + ex.getMessage());
				mNoInfo_shop5 = true;
			}
			finally
			{
				Message msg = new Message();
				msg.what = MSG_GET_SHOP5_OK;
				mHandler.sendMessage(msg);
			}
		}
	}
	
	public class GetShop6Thread extends Thread
	{
		private Context ctx;
		private Handler handler;
		private boolean isStop;

		public synchronized void stopRun()
		{
			isStop = true;
			this.interrupt();
		}

		public GetShop6Thread(Context c, Handler handler)
		{
			this.handler = handler;
			this.ctx = c;
			this.isStop = false;
		}

		public void run()
		{
			try
			{
				String server_url = "http://www.anydown.cn/pg/search.action?c=bangbang&p=" + mPackageName;;
				try
				{
					HttpConnect http = new HttpConnect();
					String result = http.connectByGetString(server_url, null);
					if (result == null || result.equals("") || result.equals("2001"))
					{
						Log.d("MyTag", "Shop azbb no response!");
						mNoInfo_shop6 = true;
					}
					else
					{
						DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
						DocumentBuilder dbuilder = dbf.newDocumentBuilder();
						InputSource is = new InputSource(new StringReader(result));
						is.setEncoding("UTF-8");
						
						Document dom = dbuilder.parse(is);
						String state = dom.getElementsByTagName("state").item(0).getTextContent();
						if(state.equals("0"))
							mNoInfo_shop6 = true;
						else
						{
							String tmpName = dom.getElementsByTagName("name").item(0).getTextContent();
							mAppName_shop6  = new String(tmpName.getBytes("ISO-8859-1"), "UTF-8");
							mAppVersion_shop6 = dom.getElementsByTagName("version").item(0).getTextContent();
							mAppSize_shop6 = dom.getElementsByTagName("size").item(0).getTextContent();
							mDownUrl_shop6 = dom.getElementsByTagName("download").item(0).getTextContent();
						}
					}
					Message msg = new Message();
					msg.what = MSG_GET_SHOP6_OK;
					mHandler.sendMessage(msg);
					
				} catch (Exception e)
				{
					Log.d("MyTag", "Shop azbb error1:" + e.getMessage());
					mNoInfo_shop6 = true;
					Message msg = new Message();
					msg.what = MSG_GET_SHOP6_OK;
					mHandler.sendMessage(msg);
				}

			} catch (Exception ex)
			{
				Log.d("MyTag", "Shop azbb error2:" + ex.getMessage());
				mNoInfo_shop6 = true;
				Message msg = new Message();
				msg.what = MSG_GET_SHOP6_OK;
				mHandler.sendMessage(msg);
			}
		}
	}
	
	public class GetShop7Thread extends Thread
	{
		private Context ctx;
		private Handler handler;
		private boolean isStop;

		public synchronized void stopRun()
		{
			isStop = true;
			this.interrupt();
		}

		public GetShop7Thread(Context c, Handler handler)
		{
			this.handler = handler;
			this.ctx = c;
			this.isStop = false;
		}

		public void run()
		{
			try
			{
				String server_url = "http://apk.angeeks.com/getAPK.do?packagename=" + mPackageName;
				try
				{
					HttpConnect http = new HttpConnect();
					String res = http.connectByGetString(server_url, null);
					if (res == null || res.equals("") || res.equals("403"))
					{
						Log.d("MyTag", "Shop Anji no response!");
						mNoInfo_shop7 = true;
					}
					else
					{
				    	JSONObject json = new JSONObject(res);
				    	mAppName_shop7 = json.getString("appName");
				    	mAppName_shop7  = new String(mAppName_shop7.getBytes("ISO-8859-1"), "GBK");
						mAppVersion_shop7 = json.getString("versionName");
						mDownUrl_shop7 = json.getString("uri");
						mAppSize_shop7 = json.getString("size");
					}
					Message msg = new Message();
					msg.what = MSG_GET_SHOP7_OK;
					mHandler.sendMessage(msg);
					
				} catch (Exception e)
				{
					Log.d("MyTag", "Shop Anji error1:" + e.getMessage());
					mNoInfo_shop7 = true;
					Message msg = new Message();
					msg.what = MSG_GET_SHOP7_OK;
					mHandler.sendMessage(msg);
				}

			} catch (Exception ex)
			{
				Log.d("MyTag", "Shop Anji error2:" + ex.getMessage());
				mNoInfo_shop7 = true;
				Message msg = new Message();
				msg.what = MSG_GET_SHOP7_OK;
				mHandler.sendMessage(msg);
			}
		}
	}

	public class ShopsAdapter extends BaseAdapter
	{
		private List<ShopItem> shopList;

		public ShopsAdapter(Context ctx, List<ShopItem> shopList)
		{
			this.shopList = shopList;
		}

		public void updateInfo(int index)
		{
			if(index == MSG_GET_SHOP2_OK)//历趣
			{
				shopList.get(indexLiqu).app_name = mAppName_shop2;
				shopList.get(indexLiqu).app_version = mAppVersion_shop2;
				shopList.get(indexLiqu).app_size = mAppSize_shop2;
				shopList.get(indexLiqu).down_url = mDownUrl_shop2;
				shopList.get(indexLiqu).noInfo = mNoInfo_shop2;
			}
			else if(index == MSG_GET_SHOP3_OK)//安丰
			{
				shopList.get(indexAnfeng).app_name = mAppName_shop3;
				shopList.get(indexAnfeng).app_version = mAppVersion_shop3;
				shopList.get(indexAnfeng).app_size = mAppSize_shop3;
				shopList.get(indexAnfeng).down_url = mDownUrl_shop3;
				shopList.get(indexAnfeng).noInfo = mNoInfo_shop3;
			}
			else if(index == MSG_GET_SHOP4_OK)//机锋
			{
				shopList.get(indexJifeng).app_name = mAppName_shop4;
				shopList.get(indexJifeng).app_version = mAppVersion_shop4;
				shopList.get(indexJifeng).app_size = mAppSize_shop4;
				shopList.get(indexJifeng).down_url = mDownUrl_shop4;
				shopList.get(indexJifeng).noInfo = mNoInfo_shop4;
			}
			else if(index == MSG_GET_SHOP5_OK)//优亿
			{
				shopList.get(indexEoe).app_name = mAppName_shop5;
				shopList.get(indexEoe).app_version = mAppVersion_shop5;
				shopList.get(indexEoe).app_size = mAppSize_shop5;
				shopList.get(indexEoe).down_url = mDownUrl_shop5;
				shopList.get(indexEoe).noInfo = mNoInfo_shop5;
			}
			else if(index == MSG_GET_SHOP6_OK)//安卓必备
			{
				shopList.get(indexAnzhuo).app_name = mAppName_shop6;
				shopList.get(indexAnzhuo).app_version = mAppVersion_shop6;
				shopList.get(indexAnzhuo).app_size = mAppSize_shop6;
				shopList.get(indexAnzhuo).down_url = mDownUrl_shop6;
				shopList.get(indexAnzhuo).noInfo = mNoInfo_shop6;
			}
			else if(index == MSG_GET_SHOP7_OK)//安极
			{
				shopList.get(indexAnji).app_name = mAppName_shop7;
				shopList.get(indexAnji).app_version = mAppVersion_shop7;
				shopList.get(indexAnji).app_size = mAppSize_shop7;
				shopList.get(indexAnji).down_url = mDownUrl_shop7;
				shopList.get(indexAnji).noInfo = mNoInfo_shop7;
			}
		}
		
		@Override
		public int getCount()
		{
			return shopList.size();
		}

		@Override
		public Object getItem(int position)
		{
			return position;
		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			FeedItem feedItem;
			if (convertView == null)
			{
				View v = LayoutInflater.from(DownloadActivity.this).inflate(R.layout.appshare_shop_item, null);
				feedItem = new FeedItem();
				feedItem.mAppName = (TextView) v.findViewById(R.id.app_name);
				feedItem.mVS = (TextView) v.findViewById(R.id.version_size);
				feedItem.mDown = (Button) v.findViewById(R.id.downBtn);
				feedItem.mShopIcon = (ImageView) v.findViewById(R.id.shopIcon);
				feedItem.mShopBroad = (TextView) v.findViewById(R.id.shopBroad);
				v.setTag(feedItem);
				convertView = v;
			} else
				feedItem = (FeedItem) convertView.getTag();

			final ShopItem shopInfo = shopList.get(position);
			feedItem.mAppName.setText(shopInfo.app_name);
			feedItem.mShopBroad.setText(shopInfo.shop_word);
			if((position == indexBang))
			{
				feedItem.mShopIcon.setVisibility(View.GONE);
			}
			else
			{
				feedItem.mShopIcon.setVisibility(View.VISIBLE);
				feedItem.mShopIcon.setImageResource(shopInfo.shop_icon);
				if(position == indexAnji)
					feedItem.mShopIcon.setOnClickListener(null);
				else
					feedItem.mShopIcon.setOnClickListener(new OnClickListener()
					{
						@Override
						public void onClick(View v)
						{
							Dialog dialog = new AlertDialog.Builder(DownloadActivity.this)
							.setIcon(android.R.drawable.ic_dialog_info)
							.setTitle("提示")
							.setMessage("确认下载" + shopInfo.shop_name + "吗？")
							.setPositiveButton("确认", new DialogInterface.OnClickListener()
							{
								@Override
								public void onClick(DialogInterface dialog, int which)
								{
									dialog.dismiss();
									DownApp.downApp(DownloadActivity.this, DownloadActivity.this, mHandler, shopInfo.shop_url, shopInfo.shop_size);
								}
							})
							.setNegativeButton("取消", new DialogInterface.OnClickListener()
							{
								@Override
								public void onClick(DialogInterface dialog, int which)
								{
									dialog.dismiss();
								}
							}).create();
							dialog.show();
						}
					});
			}
			
			
			if(shopInfo.noInfo)
				feedItem.mVS.setText("该商店无此应用信息。");
			else
			{
				String sizeStrM = "";
				try
				{
					double sizeDoubleK = Double.valueOf(shopInfo.app_size);
					double sizeDoubleM = sizeDoubleK / (1024*1024);
					DecimalFormat df = new DecimalFormat("0.00");
					sizeStrM = df.format(sizeDoubleM);
					
				} catch (Exception ex)
				{
					//Log.d("MyTag", "DecimalFormat err:" + ex.getMessage());
				}
				
				feedItem.mVS.setText("最新版：" + shopInfo.app_version + "  大小：" + sizeStrM + "M");
			}
			if (shopInfo.down_url.equals(""))
				feedItem.mDown.setVisibility(View.GONE);
			else
			{
				feedItem.mDown.setVisibility(View.VISIBLE);
				feedItem.mDown.setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						Log.d("MyTag", "Download url = " + shopInfo.down_url);
						
						if(shopInfo.app_size.equals("")){
							return;
						}
						
						Thread downLog = new Thread() 
						{
							public void run()
							{
								RemoteApiImpl remoteApi = new RemoteApiImpl();
								remoteApi.sendDownLog(DownloadActivity.this, mPackageName, shopInfo.shop_name);
							}
						};
						downLog.start();
						
						DownApp.downApp(DownloadActivity.this, DownloadActivity.this, mHandler, shopInfo.down_url, shopInfo.app_size);
						Thread shareThread = new Thread() 
						{
							public void run()
							{
								RemoteApiImpl remoteApi = new RemoteApiImpl();
								remoteApi.sendDownloadAction(DownloadActivity.this, mPackageName);
								ActivityUtil.shareToWeibo(DownloadActivity.this, Constants.UPLOAD_ACTION_DOWN, mAppName, "", mIconBytes, null, mIconUrl, mAppDes , mPackageName);

								if(!Constants.SWITCH_SINA_CUSTOM){
									if(mIconBytes != null){
										remoteApi.share2QWeiboMsg(DownloadActivity.this, Constants.UPLOAD_ACTION_DOWN, 
												mAppName,  mIconBytes, null, mAppDes, mPackageName) ;
									} else {
										remoteApi.share2QWeiboMsg(DownloadActivity.this, Constants.UPLOAD_ACTION_DOWN, 
												mAppName, null, mAppDes, mPackageName) ;
									}
								}
							}
						};
						if(false == action_msg_published){
							shareThread.start();
							action_msg_published = true;
						}
					}
				});
			}

			return convertView;
		}
	}

	class FeedItem
	{
		TextView mAppName;
		TextView mVS;
		ImageView mShopIcon;
		TextView mShopBroad;
		Button mDown;
	}

	public static void beginDownload(Activity activity, String packageName, String appName, String appVersion, String appSize, String downUrl, byte[] imageBytes, String icon_url, String appDes)
	{
		Intent intent = new Intent(activity, DownloadActivity.class);
		Bundle mBundle = new Bundle();
		mBundle.putString("package_name", packageName);
		mBundle.putString("app_name", appName);
		mBundle.putString("app_version", appVersion);
		mBundle.putString("app_size", appSize);
		mBundle.putString("down_url", downUrl);
		mBundle.putString("icon_url", icon_url);
		mBundle.putByteArray("app_icon_array", imageBytes);
		mBundle.putString("app_des", appDes);
		intent.putExtras(mBundle);
		activity.startActivity(intent);
	}
}